<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name"  placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="学号" prop="sno">
        <el-input v-model="form.sno" placeholder="请输入学号" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="form.sex" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {addStudent, getStudent, updateStudent} from "@/api/system/student"

export default {
  name: "stuAdd",
  data() {
    return {
      form: {
        name: null,
        sno: null,
        sex: null
      },
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        sno: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    // 从路由参数中获取 id
    const id = this.$route.query.id;
    if(id){
      getStudent(id).then(response => {
        this.form = response.data
      })
    }
  },
  methods: {
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.cancel()
            })
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.cancel()
            })
          }
        }
      })
    },
    cancel() {
      this.$router.push({ path: 'student' })
    }
  }
}
</script>
